package com.flyme.module.base.provider.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.flyme.common.core.model.ResultBody;
import com.flyme.common.core.model.query.CriteriaQuery;
import com.flyme.common.core.model.query.PagerInfo;
import com.flyme.common.core.model.query.PqGrid;
import com.flyme.common.core.utils.jpush.JpushPush;
import com.flyme.core.base.supper.controller.BaseController;
import com.flyme.core.base.supper.entity.EntityMap;
import com.flyme.module.base.client.api.SysMessageRemoteService;
import com.flyme.module.base.client.constants.BaseConstants;
import com.flyme.module.base.client.entity.SysMessage;
import com.flyme.module.base.client.entity.SysMessageSend;
import com.flyme.module.base.client.entity.SysUser;
import com.flyme.module.base.provider.service.SysMessageSendService;
import com.flyme.module.base.provider.service.SysMessageService;
import com.flyme.module.base.provider.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author flyme
 */
@Slf4j
@RestController
@Api(description = "消息内容管理接口")
@RequestMapping("/message")
public class SysMessageController extends BaseController<SysMessageService, SysMessage> implements SysMessageRemoteService {
    
    
    @Autowired
    private SysMessageSendService sendService;
    
    @Autowired
    private SysUserService userService;
    
    
    @PostMapping(value = "/list")
    @ApiOperation(value = "消息列表")
    @Override
    public ResultBody list(@ModelAttribute PagerInfo pagerInfo, @ModelAttribute SysMessage message) {
        CriteriaQuery cq = new CriteriaQuery<EntityMap>(pagerInfo);
        cq.select("id", "messageTitle", "messageType", "createTime","summary","sendStatus","sendType");
        cq.eq("messageType", 1);
        PqGrid pqGrid = bizService.pageList(cq);
        return ResultBody.success(pqGrid);
    }

    @GetMapping(value = "/get/{id}")
    @ApiOperation(value = "通过id获取")
    @Override
    public ResultBody get(@PathVariable String id) {
        SysMessage message = bizService.getById(id);
        return ResultBody.success().setData(message);
    }

    @PostMapping(value = "/add")
    @ApiOperation(value = "添加消息")
    @Override
    public ResultBody add(@ModelAttribute SysMessage message) {
        message.setSendStatus(0);
        message.setSendType(0);
        bizService.save(message);
        return ResultBody.ok("添加成功");
    }

    /**
     * 发送消息
     */
    @PostMapping(value = "/sendMsg")
    @ApiOperation(value = "发送消息")
    public ResultBody sendMsg(@ModelAttribute SysMessage message) {
        SysMessage oldMessage = bizService.getById(message.getId());
        // 保存消息发送表
        List<SysMessageSend> messageSends = new ArrayList<>();
        List<String> aliases = new ArrayList<>();
        if (BaseConstants.MESSAGE_RANGE_ALL.equals(message.getSendType())) {
            // 全体
            List<SysUser> allUser = userService.list();
            allUser.forEach(u -> {
                //消息时间小于用户注册时间
                Long a = DateUtil.between(oldMessage.getCreateTime(), u.getCreateTime(), DateUnit.MINUTE, false);
                if(a < 0){
                    aliases.add(u.getId().toString());
                }
            });
            // 推送
            // messagingTemplate.convertAndSend("/topic/subscribe", "您收到了新的系统消息");
        } else if(BaseConstants.MESSAGE_RANGE_COMPANY.equals(message.getSendType())){
            // 企业
            List<String> list = userService.selectAllCompany();
            aliases.addAll(list);
        } else {
            // 指定用户
            for (Long id : message.getUserIds()) {
                // 指定用户
                //messagingTemplate.convertAndSendToUser(id.toString(), "/queue/subscribe", "您收到了新的消息");
                aliases.add(id.toString());
                SysMessageSend messageSend = new SysMessageSend();
                messageSend.setMessageId(message.getId());
                messageSend.setMessageStatus(0);
                messageSend.setUserId(id);
                messageSend.setMessageType("1");
                messageSends.add(messageSend);
            }
            sendService.saveBatch(messageSends);
        }
        message.setSendStatus(1);
        message.setSendTime(DateUtil.now());
        bizService.saveOrUpdate(message);
        JpushPush jPush = new JpushPush();
        Map<String, String> msg = new HashMap<String, String>();
        String pushMsg = "您收到了新的系统消息";
        //发送推送
        msg.put("msg", pushMsg);
        msg.put("pushType", "1");
        msg.put("content", pushMsg);
        msg.put("noticeId", message.getId().toString());
        jPush.pushByAlias("COMM", aliases, pushMsg, "1", "", msg);
        return ResultBody.ok("发送成功");
    }
    
    /**
     * 构建消息发送记录
     */
    private void initMesageSendList(List<SysMessageSend> messageSends, Long userId, Long messageId) {
        SysMessageSend ms = new SysMessageSend();
        ms.setMessageId(messageId);
        ms.setUserId(userId);
        ms.setMessageStatus(BaseConstants.MESSAGE_STATUS_UNREAD);
        messageSends.add(ms);
    }
    
    @PostMapping(value = "/edit")
    @ApiOperation(value = "编辑消息")
    @Override
    public ResultBody edit(@ModelAttribute SysMessage message) {
        Boolean tag = bizService.saveOrUpdate(message);
        return ResultBody.ok("编辑成功").setData(tag);
    }
    
    @PostMapping(value = "/delByIds/{ids}")
    @ApiOperation(value = "删除消息")
    @Override
    public ResultBody del(@PathVariable Long[] ids) {
        bizService.removeByIds(CollectionUtil.toList(ids));
        // 删除发送表
        sendService.deleteByMessageId(ids);
        return ResultBody.ok("删除成功");
    }

    /*********************   新闻   ************************/

    @PostMapping(value = "/newsList")
    @ApiOperation(value = "新闻列表")
    @Override
    public ResultBody newsList(@ModelAttribute PagerInfo pagerInfo, @ModelAttribute SysMessage message) {
        CriteriaQuery cq = new CriteriaQuery<EntityMap>(pagerInfo);
        cq.select("id", "messageTitle", "messageType", "createTime","sortOrder","summary","updateTime");
        cq.eq("messageType", 3);
        cq.like("messageTitle", message.getMessageTitle());
        cq.like("messageContent", message.getMessageContent());
        cq.like("createTime", message.getCreateTime());
        cq.orderByAsc("sortOrder");
        PqGrid pqGrid = bizService.pageList(cq);
        return ResultBody.success(pqGrid);
    }

    @PostMapping(value = "/addNews")
    @ApiOperation(value = "添加新闻")
    @Override
    public ResultBody addNews(@ModelAttribute SysMessage message) {
        message.setMessageType(3);
        bizService.save(message);
        return ResultBody.ok("添加成功");
    }

    @PostMapping(value = "/delNewsByIds/{ids}")
    @ApiOperation(value = "删除新闻")
    @Override
    public ResultBody delNews(@PathVariable Long[] ids) {
        bizService.removeByIds(CollectionUtil.toList(ids));
        return ResultBody.ok("删除成功");
    }

    @PostMapping(value = "/editNews")
    @ApiOperation(value = "编辑新闻")
    @Override
    public ResultBody editNews(@ModelAttribute SysMessage message) {
        message.setCreateTime(null);
        Boolean tag = bizService.saveOrUpdate(message);
        return ResultBody.ok("编辑成功").setData(tag);
    }
}
